<template>
  <div>
    <!-- 搜索栏 -->
    <el-form
      :model="searchForm.data"
      label-width="auto"
      :ref="searchForm.ref"
      @submit.prevent="searchForm.onSubmit"
    >
      <el-form-item>
        <el-col :span="6">
          <el-form-item
            label="权限名称:"
            prop="name"
          >
            <el-input
              v-model="searchForm.data.name"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col
          :span="6"
          style="margin-left: 16px;"
        >
          <el-button
            type="primary"
            @click="searchForm.onSubmit"
          >
            <template #icon>
              <Search />
            </template>搜索</el-button>
          <el-button @click="searchForm.onClear">
            <template #icon>
              <Refresh />
            </template>重置</el-button>

        </el-col>
      </el-form-item>
      <el-form-item v-permission="['sys:usermgr:permission:add']">
        <el-button
          @click="onAdd"
          type="success"
        >
          <template #icon>
            <Plus />
          </template>新增</el-button>
      </el-form-item>
    </el-form>

    <FormDialog
      ref="dialogRef"
      :formFields="fields"
      :formHandlers="formHandlers"
      @success="onDialogSuccess"
    />
    <PTable
      :dataColumns="fields"
      :table="table"
    />

  </div>
</template>
<script lang="ts" setup>
import { addPermissionInfo, deletePermissionInfo, editPermissionInfo, getPermissionInfo, getPermissionTreeList } from '@/api/usermgr'
import { FormMode, PermissionType, PermissionTypeRatioOptions, PermissionTypeToString } from '@/common/type/baseEnum'
import FormDialog from '@/components/FormDialog.vue'
import PTable from '@/components/PTable.vue'
import type { PermissionData } from '@/common/type/data'
import type { CommonField, SelectOptions } from '@/common/type/field'
import type { SearchForm } from '@/common/type/form'
import { DefaultOperationTable, type OperationTable } from '@/common/type/table'
import Logger from '@/util/log'
import { onMounted, reactive, ref } from 'vue'
import { isResultSuccess } from '@/util/http'
import type { Result } from '@/api/http/request'
import { ElMessage } from 'element-plus'

const searchForm: SearchForm = {
  data: reactive({
    name: '',
  }),

  ref: ref(),
  onSubmit: () => {
    console.log('search submit!', searchForm.data.name)
    table.initTableData()
  },
  onClear: () => {
    searchForm.ref.value.resetFields()
    table.initTableData()
  },
}

const dialogRef = ref()
const menuList = ref<SelectOptions[]>([])

const fields: CommonField[] = [
  {
    prop: 'idx',
    label: '序号',
    formMeta: {
      hideInForm: true,
    },
    tableMeta: {
      width: '66',
      type: 'index'
    },
  },
  {
    label: '权限名称',
    prop: 'title',
    formMeta: {
      rules: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
      disabledOn: [FormMode.Edit]
    },
  },
  {
    label: '权限类型',
    prop: 'type',
    formMeta: {
      type: 'radio',
      rules: [{ required: true, message: '请选择权限类型', trigger: 'blur' }],
      options: PermissionTypeRatioOptions,
      disabledOn: [FormMode.Edit]
    },
    tableMeta: {
      width: '90',
      contentType: 'tag',
      tagMapper: {
        [PermissionType.Directory]: { text: PermissionTypeToString[PermissionType.Directory], type: 'info' },
        [PermissionType.Menu]: { text: PermissionTypeToString[PermissionType.Menu], type: 'primary' },
        [PermissionType.Operation]: { text: PermissionTypeToString[PermissionType.Operation], type: 'success' },
      },
    }
  },
  {
    label: '所属层级',
    prop: 'parent_id',
    formMeta: {
      type: 'tree-select',
      options: menuList.value,
      rules: [{ required: true, message: '请选择所属层级', trigger: 'blur' }],
    },
    tableMeta: {
      hideInTable: true,
    }
  },
  {
    label: '权限字段',
    prop: 'code',
    formMeta: {
      rules: [{ required: true, message: '请输入权限字段', trigger: 'blur' }],
    },
  },
  {
    label: '图标',
    prop: 'icon',
    tableMeta: {
      contentType: 'icon'
    }
  },
  {
    label: '显示顺序',
    prop: 'order_num',
    formMeta: {
    },
    tableMeta: {
      hideInTable: true,
    }
  },
  {
    label: "路由名称",
    prop: 'route_name',
    formMeta: {
      hideIf(formData) { return formData.type === PermissionType.Operation },
      rules: [{ required: true, message: '请输入路由名称', trigger: 'blur' }],
    },
    tableMeta: {
      hideInTable: true,
    }
  },
  {
    label: "路由路径",
    prop: 'route_path',
    formMeta: {
      hideIf(formData) { return formData.type === PermissionType.Operation },
      rules: [{ required: true, message: '请输入路由路径', trigger: 'blur' }],
    }
  },
  {
    label: "组件名称",
    prop: 'route_component',
    formMeta: {
      hideIf(formData) { return formData.type === PermissionType.Operation },
      rules: [{ required: true, message: '请输入组件名称', trigger: 'blur' }],
    }
  }
]

const findParentName = (value: number, nodes: SelectOptions[]): string => {
  for (const node of nodes) {
    if (node.value === value) {
      return node.label
    }
    if (node.children) {
      const found = findParentName(value, node.children)
      if (found) return found
    }
  }
  return ''
}

// 此函数的主要是因为非表单字段的更新需要额外的处理
const permissionInfoWrapper = (data: PermissionData): PermissionData => {
  // const p_name = findParentName(data.parent_id, menuList.value)
  Logger.prettyInfo("addPermissionInfoWapper", data.parent_id, data.order_num)
  const processedData: PermissionData = {
    ...data,
    parent_name: findParentName(data.parent_id, menuList.value),
    order_num: data.order_num ? Number(data.order_num) : undefined
  } as PermissionData
  return processedData
}
// note！！wrapper写法一定要注意，是promise类型返回值
const addPermissionInfoWrapper = (data: PermissionData): Promise<Result<any>> => {
  // 返回原始API调用结果
  return addPermissionInfo(permissionInfoWrapper(data))
}

const editPermissionInfoWrapper = (data: PermissionData): Promise<Result<any>> => {
  return editPermissionInfo(permissionInfoWrapper(data))
}

const formHandlers = new Map([
  [FormMode.Add, addPermissionInfoWrapper],
  [FormMode.Edit, editPermissionInfoWrapper],
])

const onDialogSuccess = () => {
  refreshPermissionTreeList()
  table.initTableData()
}

const onAdd = () => {
  dialogRef.value.open(FormMode.Add)
}

const table: OperationTable<PermissionData> = new DefaultOperationTable({
  rowKey: 'id', // 树形表专用
  refreshTableData: async () => {
    try {
      const res = await getPermissionInfo() // todo 先不用查询条件，后面再优化
      if (res && isResultSuccess(res)) {
        Logger.prettyInfo('getPermissionInfo', res.data)
        if (res.data.list[0]?.children) {
          table.data.splice(0, table.data.length, ...res.data.list[0]?.children)
        }
      }
    } catch (error) {
      Logger.prettyError('getPermissionInfo catch error', error)
    }
  },
  onTableDataEdit: (index: number, row: PermissionData) => {
    dialogRef.value.open(FormMode.Edit, row)
  },
  editPermissionCode: 'sys:usermgr:permission:edit',
  deletePermissionCode: 'sys:usermgr:permission:delete',
  onTableDataDelete: async (index: number, row: PermissionData) => {
    let success = false, errMsg: any
    try {
      const res = await deletePermissionInfo({ "permission_id": row.id })
      success = isResultSuccess(res)
      errMsg = res.msg
    } catch (error) {
      errMsg = error
      Logger.prettyError('deleteRoleInfo catch error', error.response.data)
    }
    if (!success) {
      ElMessage.error('删除权限失败！' + errMsg)
    } else {
      ElMessage.success('删除权限成功！')
      refreshPermissionTreeList()
      table.initTableData()
    }
  }
})

const refreshPermissionTreeList = async () => {
  const res = await getPermissionTreeList()
  if (res && isResultSuccess(res)) {
    Object.assign(menuList.value, res.data)
    // Logger.prettyInfo('getPermissionTreeList', menuList.value)
  }
}

onMounted(() => {
  refreshPermissionTreeList()
})

</script>
<style scoped></style>